﻿using System;
using System.IO;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using NCommonLib.Extensions;

namespace NPortableEngine
{
    internal class StreamScouter : IStreamScouter
    {
        internal StreamScouter(string url)
        {
            this.ImageUrl = url;
        }

        public string ImageUrl { get; private set; }

        public async Task<ScouterBackData> Fly(Type djangoType)
        {
            ScouterBackData scouterBackData = new ScouterBackData();
            WebResponse response = null;
            HttpEngine httpEngine = new HttpEngine();
            try
            {
                response = await httpEngine.Request(ImageUrl, null, null, HttpMethodType.GET, ReqType.IMAGE).ConfigureAwait(false);

                using (Stream stream = response.GetResponseStream())
                {
                    if (djangoType == typeof(byte[]))
                    {
                        scouterBackData.ResponseData = stream.ToByteArray();
                    }
                    else
                    {
                        scouterBackData.ResponseData = stream;
                    }
                }

                scouterBackData.IsSuccess = true;
                scouterBackData.Msg = "Success!";
            }
            catch
            {
                scouterBackData.IsSuccess = false;
                scouterBackData.Msg = "HttpEngine Request Error!";
            }
            finally
            {
                if (response != null)
                {
                    response.Dispose();
                    response = null;
                }
            }
            return scouterBackData;
        }

    }
}
